package com.dc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.DateUtil;
import com.dc.common.ResponseResultVO;
import com.dc.entity.*;
import com.dc.entity.ro.WareHouseRelationRO;
import com.dc.exceptions.BizException;
import com.dc.mapper.WareHouseAddressMapper;
import com.dc.mapper.WareHouseDetailMapper;
import com.dc.mapper.WareHouseMapper;
import com.dc.mapper.WareHouseRelationMapper;
import com.dc.service.WareHouseRelationService;
import com.dc.util.RedisUtil;
import com.dc.util.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.dc.common.ResponseResultVO.checkParameterIsNotNull;

@Service
public class WareHouseRelationServiceImpl extends ServiceImpl<WareHouseRelationMapper, WareHouseRelation> implements WareHouseRelationService {

    @Resource
    private WareHouseRelationMapper wareHouseRelationMapper;
    @Resource
    private WareHouseAddressMapper addressMapper;
    @Resource
    private WareHouseMapper wareHouseMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private WareHouseDetailMapper wareHouseDetailMapper;


    @Override
    @Transactional
    public ResponseResultVO insertWareHouseRelation(WareHouseRelationRO ro) {
        List<WareHouse> info = ro.getInfo();
        //出入库主记录入库
        WareHouseRelation houseRelation = new WareHouseRelation();
        BeanUtils.copyProperties(ro, houseRelation);
        houseRelation.setId(SnowflakeIdWorker.generateId());
        houseRelation.setInOutTime(DateUtil.parseStrToDate(ro.getInOutTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        houseRelation.setStockNum(info.stream().mapToInt(WareHouse::getStockNum).sum());
        houseRelation.setNumber(0 == ro.getType() ? redisUtil.serialNumber("WXPRK") : redisUtil.serialNumber("WXPCK"));
        houseRelation.setAddress(ro.getRegionName());
        wareHouseRelationMapper.insert(houseRelation);
        int insert = 0;
        //修改库存以及区域关联表库存
        for (WareHouse wareHouse : info) {
            WareHouseAddress data = addressMapper.selectOne(new QueryWrapper<WareHouseAddress>().lambda().eq(WareHouseAddress::getWareHouseId, wareHouse.getId()).eq(WareHouseAddress::getRegionName, ro.getRegionName()));
            if (null != data) {
                int num = 0;
                if (0 == ro.getType()) {
                    //入库
                    num = wareHouse.getStockNum() + data.getStockNum();
                } else {
                    //出库
                    num = data.getStockNum() - wareHouse.getStockNum();
                    if (num < 0) {
                        throw new BizException("出库数量异常!");
                    }
                }
                data.setStockNum(num);
                addressMapper.updateById(data);
            } else {
                WareHouseAddress wareHouseAddress = new WareHouseAddress();
                wareHouseAddress.setId(SnowflakeIdWorker.generateId());
                wareHouseAddress.setRegionName(ro.getRegionName());
                wareHouseAddress.setRegionId(ro.getRegionId());
                wareHouseAddress.setStockNum(wareHouse.getStockNum());
                wareHouseAddress.setWareHouseId(wareHouse.getId());
                addressMapper.insert(wareHouseAddress);
            }
            WareHouse wareHouse1 = wareHouseMapper.selectById(wareHouse.getId());
            int i = 0;
            if (0 == ro.getType()) {
                //入库
                i = wareHouse1.getStockNum() + wareHouse.getStockNum();
            } else {
                //出库
                i = wareHouse1.getStockNum() - wareHouse.getStockNum();
            }
            wareHouse1.setStockNum(i);
            wareHouseMapper.updateById(wareHouse1);

            WareHouseDetail wareHouseDetail = new WareHouseDetail();
            BeanUtils.copyProperties(wareHouse, wareHouseDetail);
            wareHouseDetail.setId(SnowflakeIdWorker.generateId());
            wareHouseDetail.setHouseId(wareHouse.getId());
            wareHouseDetail.setRelationId(houseRelation.getId());
            insert = wareHouseDetailMapper.insert(wareHouseDetail);

        }
        return ResponseResultVO.insertResult(insert);
    }

    @Override
    public ResponseResultVO updateWareHouseRelation(WareHouseRelationRO ro) {
        checkParameterIsNotNull(String.valueOf(ro.getId()), "id不能为空");
        WareHouseRelation wareHouseRelation = new WareHouseRelation();
        BeanUtils.copyProperties(ro, wareHouseRelation);
        return ResponseResultVO.updateResult(wareHouseRelationMapper.updateById(wareHouseRelation));
    }

    @Override
    public ResponseResultVO deleteWareHouseRelation(String ids) {
        checkParameterIsNotNull(ids, "id不能为空");
        List<String> idList = Arrays.asList(ids.split(","));
        return ResponseResultVO.deleteResult(wareHouseRelationMapper.deleteBatchIds(idList));
    }

    @Override
    public ResponseResultVO selectWareHouseRelationList(WareHouseRelationRO ro) {
        Page page = new Page<Map<String, Object>>(ro.getCurrentPage(), ro.getPageSize());
        LambdaQueryWrapper<WareHouseRelation> queryWrapper = new QueryWrapper<WareHouseRelation>().lambda();
        if (StringUtils.isNotBlank(ro.getNumber())) {
            queryWrapper.like(WareHouseRelation::getNumber, ro.getNumber());
        }
        if (null != ro.getType()) {
            queryWrapper.eq(WareHouseRelation::getType, ro.getType());
        }
        queryWrapper.apply(StrUtil.isNotBlank(ro.getInOutTime()),
                "date_format (in_out_time,'%Y-%m-%d') >= date_format('" + ro.getInOutTime() + "','%Y-%m-%d')");
        queryWrapper.apply(StrUtil.isNotBlank(ro.getInOutEndTime()),
                "date_format (in_out_time,'%Y-%m-%d') < date_format('" + ro.getInOutEndTime() + "','%Y-%m-%d')");
        queryWrapper.orderByDesc(WareHouseRelation::getCreateTime);
        IPage<WareHouseRelation> iPage = wareHouseRelationMapper.selectPage(page, queryWrapper);
        iPage.getRecords().forEach(s -> {
            List<WareHouseDetail> wareHouseDetails = wareHouseDetailMapper.selectList(new QueryWrapper<WareHouseDetail>().lambda().eq(WareHouseDetail::getRelationId, s.getId()));
            s.setWareHouseDetails(wareHouseDetails);
        });
        return ResponseResultVO.resultList(iPage, ro);

    }
}
